#ifndef  _M_SERVE_H__
#define  _M_SERVE_H__
#include <iostream>
#include <vector>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctime>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <sys/epoll.h>
#include <unordered_map>
#include <functional>
#include <thread>
#include <mutex>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <typeinfo>
#include <memory>
#include <condition_variable>
#include<signal.h>
#include<fstream>

#define INF 0
#define DBG 1
#define ERR 2
#define LOG_LEVEL DBG
#define LOG(level, format, ...)                                                                                        \
    do                                                                                                                 \
    {                                                                                                                  \
        if (level < LOG_LEVEL)                                                                                         \
            break;                                                                                                     \
        time_t t = time(NULL);                                                                                         \
        struct tm *ltm = localtime(&t);                                                                                \
        char tmp[32] = {0};                                                                                            \
        strftime(tmp, 31, "%H:%M:%S", ltm);                                                                            \
        fprintf(stdout, "[%p %s %s:%d] " format "\n", (void *)pthread_self(), tmp, __FILE__, __LINE__, ##__VA_ARGS__); \
    } while (0)
#define INF_LOG(format, ...) LOG(INF, format, ##__VA_ARGS__)
#define DBG_LOG(format, ...) LOG(DBG, format, ##__VA_ARGS__)
#define ERR_LOG(format, ...) LOG(ERR, format, ##__VA_ARGS__)

#define BUFFER_DEFAULT_SIZE 1024
class Buffer
{
private:
    std::vector<char> _buffer; // 缓冲区
    uint64_t _reader_idx;      // 读偏移，偏移为相对缓冲区偏移
    uint64_t _writer_idx;      // 写偏移
public:
    Buffer() : _buffer(BUFFER_DEFAULT_SIZE), _reader_idx(0), _writer_idx(0) {}
    char *Begin() { return &*_buffer.begin(); }
    // 获取当前写入位置
    char *WriterPosition() { return Begin() + _writer_idx; }
    // 获取当前读取位置
    char *ReaderPosition() { return Begin() + _reader_idx; }
    // 获取前沿空间大小
    uint64_t HeadIdelSize() { return _reader_idx; }
    // 获取后沿空间大小
    uint64_t TailIdelSize() { return _buffer.size() - _writer_idx; }
    // 获取可读数据大小
    uint64_t ReadAbleSize() { return _writer_idx - _reader_idx; }
    // 将读偏移向后移动
    void MoveReadOffset(uint64_t len)
    {
        if (len == 0)
            return;
        // 向后移动的大小必须小于可读数据大小,这样一来rpos一定一直小于wpos
        assert(len <= ReadAbleSize());
        _reader_idx += len;
    }
    // 将写偏移向后移动
    void MoveWriteOffset(uint64_t len)
    {
        assert(len <= TailIdelSize());
        _writer_idx += len;
    }
    // 确保空间足够
    void EnsureWriteSpace(uint64_t len)
    {
        if (len <= TailIdelSize())
            return;
        // 末尾空间不够移动到前面，判断前后空间之和是否足够
        if (len <= TailIdelSize() + HeadIdelSize())
        {
            uint64_t ras = ReadAbleSize();
            std::copy(ReaderPosition(), ReaderPosition() + ras, Begin());
            _reader_idx = 0; // 读位置归零，写位置归数据大小
            _writer_idx = ras;
        }
        else
        {
            // 总体空间不够，扩容在原写偏移上
            _buffer.resize(_writer_idx + len);
        }
    }
    // 读数据
    void Read(void *buf, uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::copy(ReaderPosition(), ReaderPosition() + len, (char *)buf);
    }
    void ReadAndPop(void *buf, uint64_t len)
    {
        Read(buf, len);
        MoveReadOffset(len);
    }
    std::string ReadAsString(uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::string str;
        str.resize(len);
        Read(&str[0], len); // 直接用str.c_Str的类型为const char*,这里用重载获得首元素地址
        return str;
    }
    std::string ReadAsStringAndPop(uint64_t len)
    {
        std::string str = ReadAsString(len);
        MoveReadOffset(len);
        return str;
    }
    // 写数据
    void Write(const void *data, uint64_t len)
    {
        // 保证有足够的空间写入进去
        if (len == 0)
            return;
        EnsureWriteSpace(len);
        const char *d = (const char *)data;
        std::copy(d, d + len, WriterPosition());
    }
    void WriteAndPush(const void *data, uint64_t len)
    {
        Write(data, len);
        MoveWriteOffset(len);
    }
    void WriteString(const std::string &data)
    {
        Write(data.c_str(), data.size());
    }
    void WriteStringAndPush(const std::string &data)
    {
        WriteString(data);
        MoveWriteOffset(data.size());
    }
    void WriteBuffer(Buffer &data)
    {
        return Write(data.ReaderPosition(), data.ReadAbleSize());
    }
    void WriteBufferAndPush(Buffer &data)
    {
        WriteBuffer(data);
        MoveWriteOffset(data.ReadAbleSize());
    }

    char *FindCRLF()
    {
        void *res = memchr(ReaderPosition(), '\n', ReadAbleSize());
        return (char *)res;
    }
    std::string GetLine()
    {
        char *pos = FindCRLF();
        if (pos == NULL)
        {
            return "";
        }
        return ReadAsString(pos - ReaderPosition() + 1); // 将换行符也提取出来
    }
    std::string GetLineAndPop()
    {
        std::string str = GetLine();
        MoveReadOffset(str.size());
        return str;
    }
    // 清空缓冲区
    void Clear()
    {
        // 偏移量归零，覆盖写入即可
        _reader_idx = 0;
        _writer_idx = 0;
    }
};

#define MAX_LINEN 1024
class Socket
{
private:
    int _sockfd;

public:
    Socket() : _sockfd(-1) {}
    Socket(int fd) : _sockfd(fd) {}
    ~Socket() {}
    int Fd() { return _sockfd; }
    // 创建套接字
    bool Create()
    {
        // int socket(int domain,int type,int protocol)
        _sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (_sockfd < 0)
        {
            ERR_LOG("CREATE SOKCET ERR");
            return false;
        }
        return true;
    };
    // 绑定地址
    bool Bind(uint16_t port, const std::string &ip)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(struct sockaddr_in);

        int ret = bind(_sockfd, (struct sockaddr *)&addr, len);
        if (ret < 0)
        {
            ERR_LOG("BIND SOKCET ERR");
            return false;
        }
        return true;
    };
    // 监听
    bool Listen(int backlog = MAX_LINEN)
    {
        int ret = listen(_sockfd, backlog);
        if (ret < 0)
        {
            ERR_LOG("LISTEN SOKCET ERR");
            return false;
        }
        return true;
    }
    // 连接
    bool Connect(const std::string &ip, uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(struct sockaddr_in);

        int ret = connect(_sockfd, (struct sockaddr *)&addr, len);
        if (ret < 0)
        {
            ERR_LOG("CONNECT SOKCET ERR");
            return false;
        }
        return true;
    };
    // 获取新连接
    int Accept()
    {
        // int accept(int sockfd,struct sockaddr* addr,socklen_t* len)
        int newfd = accept(_sockfd, NULL, NULL);
        if (newfd < 0)
        {
            ERR_LOG("SOCKET ACCEPT ERR");
            return 1;
        }
        return newfd;
    };
    // 接收数据
    ssize_t Recv(void *buf, size_t len, int flag = 0)
    {
        std::cout << _sockfd;
        // ssize_t recv(int sockfd,void* buf,size_t len,int flag)
        ssize_t ret = recv(_sockfd, buf, len, flag);
        // EAGAIN 当前socket的接收缓冲区没有数据了，非阻塞情况下的错误
        // EINTR 当前socket阻塞等待，被信号打断
        if (ret <= 0)
        {
            if (errno == EAGAIN || errno == EINTR)
            {
                return 0; // 表示这次没有接收到数据
            }
            ERR_LOG("SOCKET RECV FAILED!");
            return -1;
        }
        return ret;
    };
    ssize_t NonBlockRecv(void *buf, size_t len)
    {
        return Recv(buf, len, MSG_DONTWAIT); // MSG_DONTWAIT表示非阻塞
    }
    // 发送数据
    ssize_t Send(const void *buf, size_t len, int flag = 0)
    {
        ssize_t ret = send(_sockfd, buf, len, flag);
        if (ret < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
            {
                return 0; // 表示这次没有数据
            }
            ERR_LOG("SOCKET SEND FAILED!");
            return -1;
        }
        return ret;
    };
    ssize_t NonBlockSend(void *buf, size_t len)
    {
        if (len == 0)
            return 0;
        return Send(buf, len, MSG_DONTWAIT);
    }

    // 创建一个服务器端连接
    bool CreateServer(uint16_t port, const std::string &ip = "0.0.0.0", bool block_flag = false)
    {
        // 1.创建套接字设置为非阻塞 2.绑定 3.监听 4.地址复用
        if (Create() == false)
            return false;
        if (block_flag == true)
            NonBlock();
        if (Bind(port, ip) == false)
            return false;
        if (Listen() == false)
            return false;
        ReuseAddress();
        return true;
    };
    // 创建一个客户端连接
    bool CreateClient(uint16_t port, const std::string &ip)
    {
        // 创建套接字 连接
        if (Create() == false)
            return false;
        if (Connect(ip, port) == false)
            return false;
        return true;
    };
    // 开启地址端重用
    void ReuseAddress()
    {
        // int setsockopt(int fd, int leve, int optname, void *val, int vallen)
        int val = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, (void *)&val, sizeof(int));
        val = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEPORT, (void *)&val, sizeof(int));
    };
    // 设置为非阻塞
    void NonBlock()
    {
        // int fcntl(int fd, int cmd, ... /* arg */ );
        int flag = fcntl(_sockfd, F_GETFL, 0);
        fcntl(_sockfd, F_SETFL, flag | O_NONBLOCK);
    };
    // 关闭套接字
    void Close()
    {
        close(_sockfd);
    };
};

class Poller;
class EventLoop;
class Channel
{
private:
    EventLoop *_loop;
    int _fd;
    uint32_t _events;
    uint32_t _revents;
    using EventCallback = std::function<void()>;
    EventCallback _read_callback;  // 可读事件被触发回调
    EventCallback _write_callback; // 可写事件被触发回调
    EventCallback _error_callback; // 错误事件被触发回调
    EventCallback _close_callback; // 连接断开事件被触发事件回调
    EventCallback _event_callback; // 任意事件被触发回调
public:
    Channel(EventLoop *loop, int fd) : _fd(fd), _events(0), _revents(0), _loop(loop) {};
    int Fd() { return _fd; }
    uint32_t Events() { return _events; } // 获取想要监控的事件
    void SetREvents(uint32_t events) { _revents = events; }
    void SetReadCallback(const EventCallback &cb) { _read_callback = cb; };
    void SetWriteCallback(const EventCallback &cb) { _write_callback = cb; };
    void SetErrorCallback(const EventCallback &cb) { _error_callback = cb; };
    void SetCloseCallback(const EventCallback &cb) { _close_callback = cb; };
    void SetEventCallback(const EventCallback &cb) { _event_callback = cb; };

    bool ReadAble() { return _revents & EPOLLIN; };   // 当前是否可读
    bool WriteAble() { return _revents & EPOLLOUT; }; // 当前是否可写
    void EableRead()
    {
        _events |= EPOLLIN;
        Updata();
    }; // 启动读事件监控
    void EableWrite()
    {
        _events |= EPOLLOUT;
        Updata();
    }; // 启动写事件监控
    void DisableRead()
    {
        _events &= ~EPOLLIN;
        Updata();
    }; // 关闭读事件监控
    void DisableWrite()
    {
        _events &= ~EPOLLOUT;
        Updata();
    }; // 关闭写事件监控
    void DisableAll()
    {
        _events = 0;
        Updata();
    }; // 关闭所有事件监控
    void Remove(); // 移除监控
    void Updata();

    void HandleEvent()
    {

        if ((_revents & EPOLLIN) || (_revents & EPOLLRDHUP) || (_revents & EPOLLPRI))
        {
            if (_read_callback)
            {
                _read_callback();
            }
        }
        // 又可能释放连接的操作一次只触发一个

        if (_revents & EPOLLOUT)
        {
            if (_event_callback)
                _event_callback();
            if (_write_callback)
                _write_callback();
        }
        else if (_revents & EPOLLERR)
        {
            if (_event_callback)
                _event_callback();
            if (_error_callback)
                _error_callback();
        }
        else if (_revents & EPOLLHUP)
        {
            if (_event_callback)
                _event_callback();
            if (_close_callback)
                _close_callback();
        }

    }; // 事件处理，一旦连续触发事件，调用这个函数，自己决定事件如何处理
};

#define MAX_EPOLLEVENTS 1024
class Poller
{
private:
    int _epfd;
    std::unordered_map<int, Channel *> _channels;
    struct epoll_event _evs[MAX_EPOLLEVENTS];

private:
    // 对epoll直接操作
    void Updata(Channel *channel, int opt)
    {
        int fd = channel->Fd();
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = channel->Events();
        int ret = epoll_ctl(_epfd, opt, fd, &ev);
        if (ret < 0)
        {
            ERR_LOG("EPOLL CTL ERROR");
            abort(); // 退出程序
        }
        return;
    };
    bool HashChannel(Channel *channels)
    {
        auto it = _channels.find(channels->Fd());
        if (it == _channels.end())
        {
            return false;
        }
        return true;
    }

public:
    Poller()
    {
        _epfd = epoll_create(MAX_EPOLLEVENTS);
        if (_epfd < 0)
        {
            ERR_LOG("EPOLL CREATE ERR");
            abort();
        }
    };
    // 添加或者修改监控文件
    void UpdtaEvent(Channel *channels)
    {
        bool ret = HashChannel(channels);
        if (ret == false) // 添加
        {
            _channels[channels->Fd()] = channels;
            return Updata(channels, EPOLL_CTL_ADD);
        }
        return Updata(channels, EPOLL_CTL_MOD);
    }
    // 移除监控
    void RemoveEvent(Channel *channels)
    {
        auto it = _channels.find(channels->Fd());
        if (it != _channels.end())
        {
            _channels.erase(it);
        }
        Updata(channels, EPOLL_CTL_DEL);
    }
    // 开始监控返回活跃连接
    void Poll(std::vector<Channel *> *active)
    {
        int nfs = epoll_wait(_epfd, _evs, MAX_EPOLLEVENTS, -1);
        if (nfs < 0)
        {
            if (errno == EINTR)
            {
                return;
            }
            ERR_LOG("EPOLL WAIT ERR,%s", strerror(errno));
            abort();
        }
        for (int i = 0; i < nfs; i++)
        {
            auto it = _channels.find(_evs[i].data.fd);
            assert(it != _channels.end());
            it->second->SetREvents(_evs[i].events); // 设置实际就绪的事件
            active->push_back(it->second);
        }
    }
};

using TaskFunc = std::function<void()>;
using ReleaseFunc = std::function<void()>;
class TimerTask
{
private:
    uint64_t _id;      // 定时器任务的对象编号
    uint32_t _timeout; // 定时器超时时间
    bool _cancel;
    TaskFunc _task_cb; // 定时器要执行的任务
    ReleaseFunc _rf;   // 用来删除定时任务
public:
    TimerTask(uint64_t id, uint32_t timeset, TaskFunc cb) : _id(id), _timeout(timeset), _task_cb(cb), _cancel(false) {}
    ~TimerTask()
    {
        if (_cancel == false)
            _task_cb();
        _rf();
    }
    void SetRealse(ReleaseFunc cb) { _rf = cb; }
    void Cancel() { _cancel = true; }
    uint32_t DelayTime() { return _timeout; }
};

class TimerWheel
{
private:
    using WeakTask = std::weak_ptr<TimerTask>;
    using PtrTask = std::shared_ptr<TimerTask>;
    int _tick;     // 指针，指到哪里哪里执行任务
    int _capacity; // 表盘最大数量，最大延迟时间
    std::vector<std::vector<PtrTask>> _wheel;
    std::unordered_map<uint64_t, WeakTask> _timers;

    EventLoop *_loop;
    int _timefd; // 定时器描述符
    std::unique_ptr<Channel> _timer_channel;

private:
    void RemoveTimer(uint64_t id)
    {
        auto it = _timers.find(id);
        if (it != _timers.end())
        {
            _timers.erase(it);
        }
    }

    static int CreateTimeFd()
    {
        int timefd = timerfd_create(CLOCK_MONOTONIC, 0);
        if (timefd < 0)
        {
            ERR_LOG("CREATE TIMER ERROR");
            abort();
        }
        struct itimerspec itime;
        itime.it_value.tv_sec = 1;
        itime.it_value.tv_nsec = 0;
        itime.it_interval.tv_sec = 1;
        itime.it_interval.tv_nsec = 0;
        timerfd_settime(timefd, 0, &itime, NULL);
        return timefd;
    }

    void ReadTimer()
    {
        uint64_t timers;
        int ret = read(_timefd, &timers, 8);
        if (ret < 0)
        {
            ERR_LOG("READ TIMERFD FAILED");
            abort();
        }
        return;
    }
    void RunTimerTask()
    {
        _tick = (_tick + 1) % _capacity;
        _wheel[_tick].clear(); // 清空当前表盘刻度下的shared，自动执行析构函数
    }
    void Ontime()
    {
        ReadTimer();
        RunTimerTask();
    }

    void TimerAddInLoop(uint64_t id, uint32_t delay, TaskFunc cb) // 新增定时任务
    {
        PtrTask pt = std::make_shared<TimerTask>(id, delay, cb);
        pt->SetRealse(std::bind(&TimerWheel::RemoveTimer, this, id));
        _timers[id] = WeakTask(pt);
        int pos = (_tick + pt->DelayTime()) % _capacity;
        _wheel[pos].push_back(pt);
    };
    void TimerRefreshInLoop(uint64_t id) // 刷新定时任务，当有新连接到来,通过weakptr找到对应id生成一个shared令count++;
    {
        auto it = _timers.find(id);
        if (it == _timers.end())
        {
            return;
        }
        PtrTask pt = it->second.lock(); // 获取对应weak的shared
        int pos = (_tick + pt->DelayTime()) % _capacity;
        _wheel[pos].push_back(pt);
    };

    void TimerCancelInLoop(uint64_t id)
    {
        auto it = _timers.find(id);
        if (it == _timers.end())
        {
            return;
        }
        PtrTask pt = it->second.lock();
        if (pt)
            pt->Cancel();
    }

public:
    TimerWheel(EventLoop *loop) : _capacity(60), _tick(0), _wheel(_capacity), _loop(loop), _timefd(CreateTimeFd()), _timer_channel(new Channel(_loop, _timefd))
    {
        _timer_channel->SetReadCallback(std::bind(&TimerWheel::Ontime, this));
        _timer_channel->EableRead();
    }

    // times有可能在多线程中进行操作，需要考虑线程安全问题，不加锁，把定时器的所有操作放到一个线程当中
    void TimerAdd(uint64_t id, uint32_t delay, TaskFunc cb);
    void TimerRefresh(uint64_t id);
    void TimerCancel(uint64_t id);

    // 这个函数存在线程安全问题，只能在模块内，对应的eventloop内使用
    bool HasTimer(uint64_t id)
    {
        auto it = _timers.find(id);
        if (it == _timers.end())
        {
            return false;
        }
        return true;
    }
};

class EventLoop
{
private:
    using Functor = std::function<void()>;
    std::thread::id _thread_id; // 线程ID
    int _event_fd;              // eventfd唤醒IO事件监控有可能导致的阻塞
    std::unique_ptr<Channel> _event_channel;
    Poller _poller;              // 所有描述符的事件监控
    std::vector<Functor> _tasks; // 任务池
    std::mutex _mutex;           // 实现任务池的线程安全

    TimerWheel _timer_wheel;

private:
    void RunAllTask()
    {
        std::vector<Functor> functor;
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            _tasks.swap(functor);
        }
        for (auto &f : functor)
        {
            f();
        }
    };
    static int CreateEventFd()
    {
        int efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
        if (efd < 0)
        {
            ERR_LOG("CREATE EVENTFD ERR");
            abort();
        }
        return efd;
    }
    void ReadEventFd()
    {
        uint64_t res = 0;
        int ret = read(_event_fd, &res, sizeof(res));
        if (res < 0)
        {
            if (errno == EINTR || errno == EAGAIN)
            {
                return;
            }
            ERR_LOG("READ EVENTFD FALIED");
            abort();
        }
        return;
    }

    void WakeUpEventFd()
    {
        uint64_t val = 1;
        int ret = write(_event_fd, &val, sizeof(val));
        if (ret < 0)
        {
            if (errno == EINTR)
            {
                return;
            }
            ERR_LOG("READ EVENTFD FALIED");
            abort();
        }
    }

public:
    EventLoop() : _thread_id(std::this_thread::get_id()), _event_fd(CreateEventFd()), _event_channel(new Channel(this, _event_fd)), _timer_wheel(this)
    {
        // 给eventfd添加可读事件回调，读取eventfd的事件通知次数
        _event_channel->SetReadCallback(std::bind(&EventLoop::ReadEventFd, this));
        // 启动eventfd的读事件监控
        _event_channel->EableRead();
    };

    // 监控事件-》就绪事件处理-》执行任务
    void Start()
    {
        while (1)
        {
            std::vector<Channel *> actives;
            _poller.Poll(&actives);
            for (auto &channel : actives)
            {
                channel->HandleEvent();
            }
            RunAllTask();
        }
    };
    // 当前线程是否是eventloop对应的线程
    bool IsInLoop()
    {
        return (_thread_id == std::this_thread::get_id());
    };

    void AssertInLoop()
    {
        assert(_thread_id == std::this_thread::get_id());
    }
    // 判断要执行的任务是否处于当前线程，是则执行，不是则压入队列
    void RunInLoop(const Functor &cb)
    {
        if (IsInLoop())
        {
            return cb();
        }
        return QueueInLoop(cb);
    };

    // 将操作压入任务池
    void QueueInLoop(const Functor &cb)
    {
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _tasks.push_back(cb);
        }
        // 唤醒可能因为没有事件就绪而导致的epoll阻塞
        WakeUpEventFd();
    };

    // 添加/修改文件描述符
    void UpdateEvent(Channel *channel)
    {
        return _poller.UpdtaEvent(channel);
    };
    // 移除文件描述符
    void RemoveEvent(Channel *channel)
    {
        return _poller.RemoveEvent(channel);
    };

    void TimerAdd(uint64_t id, uint32_t delay, const TaskFunc &cb) { return _timer_wheel.TimerAdd(id, delay, cb); }
    void TimerRefresh(uint64_t id) { return _timer_wheel.TimerRefresh(id); }
    void TimerCancel(uint64_t id) { return _timer_wheel.TimerCancel(id); }
    bool HasTimer(uint64_t id) { return _timer_wheel.HasTimer(id); }
};

class LoopThread
{
private:
    // 用于实现_loop获取的同步关系，避免创建线程，但_loop还灭有实例化之前去获取_loop
    std::mutex _mutex;             // 互斥锁
    std::condition_variable _cond; // 条件变量
    EventLoop *_loop;
    std::thread _thread;

private:
    // 实例化EventLoop对象，唤醒cond上阻塞的线程,并且开始运行EventLoop模块的功能
    void ThreadEntry()
    {
        EventLoop loop;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _loop = &loop;
            _cond.notify_all();
        }
        loop.Start();
    };

public:
    // 创建线程设定线程入口函数
    LoopThread() : _loop(NULL), _thread(std::thread(&LoopThread::ThreadEntry, this))
    {
    }
    EventLoop *GetLoop()
    {
        EventLoop *loop;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond.wait(lock, [&]()
                       { return _loop != NULL; });
            loop = _loop;
        }
        return loop;
    }
};

class LoopThreadPool
{
private:
    int _thread_cout;
    int _next_idx;
    EventLoop *_baseloop; // 主EventLoop，运行在主线程中，若——thread——cout为0则所有操作在——baseloop中执行
    std::vector<LoopThread *> _threads;
    std::vector<EventLoop *> _loops;

public:
    LoopThreadPool(EventLoop *loop) : _baseloop(loop), _thread_cout(0), _next_idx(0)
    {
    }
    void Create()
    {
        if (_thread_cout > 0)
        {
            _threads.resize(_thread_cout);
            _loops.resize(_thread_cout);
            for (int i = 0; i < _thread_cout; i++)
            {
                _threads[i] = new LoopThread();
                _loops[i] = _threads[i]->GetLoop();
            }
        }
        return;
    }
    void SetThreadCount(int count) { _thread_cout = count; }
    EventLoop *NextLoop()
    {
        if (_thread_cout == 0)
        {
            return _baseloop;
        }
        _next_idx = (_next_idx + 1) % _thread_cout;
        return _loops[_next_idx];
    }
};
class Any
{
private:
    class holder
    {
    public:
        virtual const std::type_info &type() = 0; // 获取子类保存的数据类型
        virtual holder *clone() = 0;              // 针对当前对象自身，clone出新的子类对象
        virtual ~holder() {};
    };
    template <typename T>
    class placeholder : public holder
    {
    public:
        placeholder(const T &val) : _val(val) {}
        virtual const std::type_info &type() { return typeid(T); }    // 获取子类保存的数据类型
        virtual holder *clone() { return new placeholder<T>(_val); }; // 针对当前对象自身，clone出新的子类对象;
    public:
        T _val;
    };
    holder *_content;

public:
    Any() : _content(NULL) {}
    template <class T>
    Any(const T &val) : _content(new placeholder<T>(val)) {}
    Any(const Any &other) : _content(other._content ? other._content->clone() : NULL) {}
    ~Any() { delete _content; }

    template <typename T>
    T *get()
    {
        assert(typeid(T) == _content->type());
        return &((placeholder<T> *)_content)->_val;
    };

    Any &swap(Any &other)
    {
        std::swap(_content, other._content);
        return *this;
    }
    template <typename T>
    // 赋值重载
    Any &operator=(const T &val)
    {
        // 为当前val构造any对象并做交换,此时原先指针被交换到临时变量里面，当对象释放的时候指针也被释放
        any(val).swap(*this);
        return *this;
    };
    Any &operator=(const Any &other)
    {
        Any(other).swap(*this);
        return *this;
    };
};

class Connection;
// DISCONECTED -- 连接关闭状态；   CONNECTING -- 连接建立成功-待处理状态
// CONNECTED -- 连接建立完成，各种设置已完成，可以通信的状态；  DISCONNECTING -- 待关闭状态
typedef enum
{
    DISCONECTED,
    CONNECTING,
    CONNECTED,
    DISCONNECTING
} ConnStatu;
using PtrConnection = std::shared_ptr<Connection>;
class Connection : public std::enable_shared_from_this<Connection>
{
private:
    uint64_t _conn_id;
    // uint64_t _timerid定时器ID简化用_coon_id作为timer_id
    int _sockfd;                   // 连接关联的文件描述符
    bool _enable_inactive_release; // 连接是否启动非活跃销毁的判断标志，默认为false
    EventLoop *_loop;
    ConnStatu _statu;
    Socket _socket;     // 套接字操作管理
    Channel _channel;   // 连接的事件管理
    Buffer _in_buffer;  // 输入缓冲区-----存放从socket中读取到的数据，配合message处理
    Buffer _out_buffer; // 输出缓冲区
    Any _context;       // 请求的接收处理上下文

private:
    // 这四个回调函数，是让服务器模块来设置的（其实服务器模块的处理回调也是组件使用者设置的 ）
    using MessageCallback = std::function<void(const PtrConnection &, Buffer *)>;
    using ConnectedCallback = std::function<void(const PtrConnection &)>;
    using ClosedCallback = std::function<void(const PtrConnection &)>;
    using AnyEventCallback = std::function<void(const PtrConnection &)>;

    ConnectedCallback _connected_callback;
    MessageCallback _message_callback;
    ClosedCallback _close_callback;
    AnyEventCallback _event_callback;
    ClosedCallback _server_closed_callback;

private:
    // 五个channel事件的回调，socket回调后，主要负责上层业务的处理

    // 描述符可读事件触发后调用的事件，接收socket数据放到接收缓冲区中，然后调用_message_callback
    void HandleRead()
    {
        char buf[65536];
        int ret = _socket.NonBlockRecv(buf, 65536);
        if (ret < 0)
        {
            return ShutDownInLoop();
        }
        // 将数据放入缓 冲区
        _in_buffer.WriteAndPush(buf, ret);
        if (_in_buffer.ReadAbleSize() > 0)
        {
            return _message_callback(shared_from_this(), &_in_buffer);
        }
    };

    // 描述符可写事件触发后调用的函数，将发送缓冲区中的数据进行发送
    void HandleWrite()
    {
        //_out_buffer中保存的就是要发送的数据
        ssize_t ret = _socket.NonBlockSend(_out_buffer.ReaderPosition(), _out_buffer.ReadAbleSize());
        if (ret < 0)
        {
            // 发送错误就该关闭文件了
            if (_in_buffer.ReadAbleSize() > 0)
            {
                _message_callback(shared_from_this(), &_in_buffer);
            }
            return Release();
        }
        _out_buffer.MoveReadOffset(ret); // 一定发送完把读偏移向后偏移
        // //如果当前是连接关闭状态，则有数据，发送完数据释放连接，没有数据直接释放
        if (_out_buffer.ReadAbleSize() == 0)
        {
            _channel.DisableWrite();
            if (_statu == DISCONNECTING)
            {
                return Release();
            }
        }
        return;
    };
    // 描述符触发挂断事件
    void HandleClose()
    {
        // 一旦连接挂断，套接字就什么都干不了了，因此有数据待处理就处理一下
        if (_in_buffer.ReadAbleSize() > 0)
        {
            _message_callback(shared_from_this(), &_in_buffer);
        }
        return Release();
    };
    // 描述符触发出错事件
    void HandleError()
    {
        // 一旦连接挂断，套接字就什么都干不了了，因此有数据待处理就处理一下
        if (_in_buffer.ReadAbleSize() > 0)
        {
            _message_callback(shared_from_this(), &_in_buffer);
        }
        return ReleaseInLoop();
    };
    // 描述符触发任意事件
    void HandleEvent()
    {
        // 刷新任务活跃度，调用组件使用者的任意回调
        if (_enable_inactive_release == true)
        {
            _loop->TimerRefresh(_conn_id);
        }
        if (_event_callback)
            _event_callback(shared_from_this());
    };

    // 连接获取之后，所处的状态下要进行各种设置（给channel设置事件回调，启动读监控）
    void EstablishedInLoop()
    {
        // 1.修改连接状态 2.启动读事件监控 3.事件回调调用
        assert(_statu == CONNECTING); // 当前事件必须为上层半连接状态
        _statu = CONNECTED;
        _channel.EableRead();
        if (_connected_callback)
            _connected_callback(shared_from_this());
    };
    // 实际释放接口
    void ReleaseInLoop()
    {
        DBG_LOG("RELEASE 被调用");
        // 1.修改连接状态
        _statu = DISCONNECTING;
        // 2.移除连接的事件监控
        _channel.Remove();
        // 3.关闭连接符
        _socket.Close();
        // 4.当前队列还有定时器队列中还有定时销毁任务，则取消任务
        if (_loop->HasTimer(_conn_id))
        {
            CancelInactiveReleaseInLoop();
        }
        // 5.调用关闭回调函数
        if (_close_callback)
            _close_callback(shared_from_this());
        // 5.移除服务器内部的连接信息
        if (_server_closed_callback)
            _server_closed_callback(shared_from_this());
    };

    // 这个接口并不是实际发送接口，而是把数据放到了发送缓冲区，启动可读事件监控
    void SendInLoop(Buffer buf)
    {
        if (_statu == DISCONECTED)
            return;
        _out_buffer.WriteBufferAndPush(buf);
        if (_channel.WriteAble() == false)
        {
            _channel.EableWrite();
        }
    };
    void ShutDownInLoop()
    {
        _statu = DISCONNECTING; // 设置连接为半g关闭连接状态
        if (_in_buffer.ReadAbleSize() > 0)
        {
            if (_message_callback)
                _message_callback(shared_from_this(), &_in_buffer);
        }
        // 要么就是写入数据的时候出错关闭，要么就是没有待发送数据，直接关闭
        if (_out_buffer.ReadAbleSize() > 0)
        {
            if (_channel.WriteAble() == false)
            {
                _channel.EableWrite();
            }
        }
        if (_out_buffer.ReadAbleSize() == 0)
        {
            ReleaseInLoop();
        }
    };
    // 启动非活跃连接超时释放规则
    void EnableInactiveReleaseInLoop(int sec)
    {
        _enable_inactive_release = true;
        if (_loop->HasTimer(_conn_id))
        {
            return _loop->TimerRefresh(_conn_id);
        }
        return _loop->TimerAdd(_conn_id, sec, std::bind(&Connection::Release, this));
    };
    // 取消非活跃销毁任务
    void CancelInactiveReleaseInLoop()
    {
        _enable_inactive_release = false;
        if (_loop->HasTimer(_conn_id))
            _loop->TimerCancel(_conn_id);
    };
    void UpgradeInLoop(
        const Any &context,
        const ConnectedCallback &conn,
        const MessageCallback &msg,
        const ClosedCallback &closed,
        const AnyEventCallback &event)
    {
        _context = context;
        _connected_callback = conn;
        _message_callback = msg;
        _close_callback = closed;
        _event_callback = event;
    };

public:
    Connection(EventLoop *loop, uint64_t conn_id, int sockfd)
        : _conn_id(conn_id), _sockfd(sockfd), _loop(loop),
          _enable_inactive_release(false), _statu(CONNECTING),
          _socket(sockfd), _channel(loop, sockfd)
    {
        _channel.SetCloseCallback(std::bind(&Connection::HandleClose, this));
        _channel.SetEventCallback(std::bind(&Connection::HandleEvent, this));
        _channel.SetReadCallback(std::bind(&Connection::HandleRead, this));
        _channel.SetWriteCallback(std::bind(&Connection::HandleWrite, this));
        _channel.SetEventCallback(std::bind(&Connection::HandleEvent, this));
        _channel.SetErrorCallback(std::bind(&Connection::HandleError, this));
    };
    ~Connection()
    {
        DBG_LOG("RELEASE CONNECTION:%p", this); // 我看到了就是这里
    };
    int Fd() { return _sockfd; }
    int Id() { return _conn_id; }
    bool Connected() { return _statu == CONNECTED; }
    void SetContext(const Any &context) { _context = context; }
    Any *GetContext() { return &_context; }
    void SetConnectedCallback(const ConnectedCallback &cb) { _connected_callback = cb; }
    void SetMessageCallback(const MessageCallback &cb) { _message_callback = cb; }
    void SetClosedCallback(const ClosedCallback &cb) { _close_callback = cb; }
    void SetAnyEventCallback(const AnyEventCallback &cb) { _event_callback = cb; }
    void SetSrvClosedCallback(const ClosedCallback &cb) { _server_closed_callback = cb; }

    void Establish()
    {
        _loop->RunInLoop(std::bind(&Connection::EstablishedInLoop, this));
    }

    // 发送数据，将数据放到发送缓冲区，启动写事件监控
    void Send(const char *data, size_t len)
    {
        Buffer buf;
        buf.WriteAndPush(data, len);
        _loop->RunInLoop(std::bind(&Connection::SendInLoop, this, buf));
    };
    // 提供给组件使用者的关闭接口---需要判断缓冲区是否还有数据
    void ShutDown()
    {
        _loop->RunInLoop(std::bind(&Connection::ShutDownInLoop, this));
    };

    void Release()
    {
        _loop->RunInLoop(std::bind(&Connection::ReleaseInLoop, this));
    }
    // 启动非活跃销毁，并定义多长时间无通信就是非活跃，添加定时任务
    void EnableInactiveRelease(int sec)
    {
        _loop->RunInLoop(std::bind(&Connection::EnableInactiveReleaseInLoop, this, sec));
    };

    // 取消非活跃销毁
    void CancelInactiveRelease()
    {
        _loop->RunInLoop(std::bind(&Connection::CancelInactiveReleaseInLoop, this));
    }
    // 切换协议---重置上下文即阶段性处理函数
    void Upgrade(const Any &context, const ConnectedCallback &conn, const MessageCallback &msg,
                 const ClosedCallback &closed, const AnyEventCallback &event)
    {
        _loop->AssertInLoop();
        _loop->RunInLoop(std::bind(&Connection::UpgradeInLoop, this, context, conn, msg, closed, event));
    }
};

class Acceptor
{
private:
    Socket _socket;
    Channel _channel;
    EventLoop *_loop;

    using AcceptCallback = std::function<void(int)>;
    AcceptCallback _accept_callback;

private:
    void HandleRead()
    {
        int newsocketfd = _socket.Accept();
        if (newsocketfd < 0)
        {
            return;
        }
        if (_accept_callback)
            _accept_callback(newsocketfd);
    }
    int CreateServe(uint16_t port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret == true);
        return _socket.Fd();
    }

public:
    Acceptor(EventLoop *loop, uint16_t port) : _socket(CreateServe(port)), _loop(loop), _channel(loop, _socket.Fd())
    {
        _channel.SetReadCallback(std::bind(&Acceptor::HandleRead, this));
    }
    void SetAcceptorCallback(const AcceptCallback &cb) { _accept_callback = cb; }
    void Listen() { _channel.EableRead(); }
    ~Acceptor() {}
};


class TcpServe
{
private:
    int _port;
    uint64_t _next_id;                                  // 自动增长的连接ID
    int _timeout;                                       // 非活跃销毁时间
    bool _enable_inactive_release;                      // 是否启动非活跃标志位
    EventLoop _baseloop;                                // 主线程的EventLoop对象，负责监听事件的处理
    Acceptor _acceptor;                                 // 监听套接字管理对象
    LoopThreadPool _pool;                               // 从属EventLoop线程池
    std::unordered_map<uint64_t, PtrConnection> _conns; // 保存管理所有连接对应的shared——ptr对象

private:
    using MessageCallback = std::function<void(const PtrConnection &, Buffer *)>;
    using ConnectedCallback = std::function<void(const PtrConnection &)>;
    using ClosedCallback = std::function<void(const PtrConnection &)>;
    using AnyEventCallback = std::function<void(const PtrConnection &)>;
    using Functor = std::function<void()>;

    ConnectedCallback _connected_callback;
    MessageCallback _message_callback;
    ClosedCallback _close_callback;
    AnyEventCallback _event_callback;
    ClosedCallback _server_closed_callback;

private:
    void RunAfterInLoop(const Functor &task, int delay)
    {
        _next_id++;
        _baseloop.TimerAdd(_next_id, delay, task);
    }
    void NewConnection(int fd)
    {
        _next_id++;
        PtrConnection conn(new Connection(_pool.NextLoop(), _next_id, fd));

        conn->SetMessageCallback(_message_callback);
        conn->SetConnectedCallback(_connected_callback);
        conn->SetClosedCallback(_close_callback);
        conn->SetAnyEventCallback(_event_callback);
        conn->SetSrvClosedCallback(std::bind(&TcpServe::RemoveConnection, this, std::placeholders::_1));
        if (_enable_inactive_release)
            conn->EnableInactiveRelease(_timeout); // 启动非活跃销毁
        conn->Establish();                         //
        _conns.insert(std::make_pair(_next_id, conn));
    };
    void RemoveConnectionInLoop(const PtrConnection &conn)
    {
        int id = conn->Id();
        auto it = _conns.find(id);
        if (it != _conns.end())
        {
            _conns.erase(it);
        }
    }
    // 从管理Connection的_conns中移除连接信息
    void RemoveConnection(const PtrConnection &conn)
    {
        _baseloop.RunInLoop(std::bind(&TcpServe::RemoveConnectionInLoop, this, conn));
    }

public:
    TcpServe(int port) : _port(port), _next_id(0), _enable_inactive_release(false), _acceptor(&_baseloop, port), _pool(&_baseloop) 
    {
         _acceptor.SetAcceptorCallback(std::bind(&TcpServe::NewConnection, this, std::placeholders::_1));
         _acceptor.Listen();//将监听套接字挂到baseloop上
    };
    void SetThreadCount(int cout) {return _pool.SetThreadCount(cout);};
    void SetConnectedCallback(const ConnectedCallback &cb) { _connected_callback = cb; }
    void SetMessageCallback(const MessageCallback &cb) { _message_callback = cb; }
    void SetClosedCallback(const ClosedCallback &cb) { _close_callback = cb; }
    void SetAnyEventCallback(const AnyEventCallback &cb) { _event_callback = cb; }
    void SetSrvClosedCallback(const ClosedCallback &cb) { _server_closed_callback = cb; }
    void EnableInactiveRelease(int timeout)
    {
        _timeout = timeout;
        _enable_inactive_release = true;
    }
    void RunAfter(const Functor &task, int delay) {}; // 定时任务
    void Start() { _pool.Create();  _baseloop.Start();  };
};
void Channel::Remove() { _loop->RemoveEvent(this); };
void Channel::Updata() { _loop->UpdateEvent(this); }
void TimerWheel::TimerAdd(uint64_t id, uint32_t delay, TaskFunc cb)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerAddInLoop, this, id, delay, cb));
} // 新增定时任务

void TimerWheel::TimerRefresh(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerRefreshInLoop, this, id));
}

void TimerWheel::TimerCancel(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerCancelInLoop, this, id));
}

struct NetWork
{
    NetWork()
    {
        signal(SIGPIPE,SIG_IGN);           ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    }
};

static NetWork nw;                                             ///////////////////////////////////////////////////
                                       
#endif                           //////////////////////////                                                                     
/*


                a la MUDUO 高并发服务器                                                                                                     
                                                                                                                                     ^                                          |
                                                                                                                                    ^^^                                         |      
                                                                                                                                    | |                                         |
                                      .::!!!!!!!:.                                                                                 / /                                          |
     .!!!!:.                         .:!!!!!!!!!!!!                                                                               / /                                           |         
     ~~~~!!!!!!.                 .:!!!!!!!!LINUX$$$                                                                              / (                                            |
         :$$XSX!!:           .:!!!!!!!!!!XUSEN$$$$Z                                                                             / (                                             |
         $$$$$##XS!:      .<!!!!YB$$$$"  $$$$$$$$#                                                                             / /                                              |  E58B92
         $$$$$   $$YB   :!!XS$$$$$$$$$   4$$$$$*                                                                                                                                |  E5909B
         ^$$$$   $$$\     $$$$$$$$$$$$   W$$WR"                                                                                                                                 |  E6839C
           ""$bd$$$$      .*$$$$$$$$$$MUDUO"                                                                                                                                    |  E58F96
                """"          """""                                                                                                                                             |  E5B091
                                                                                                                                                                                |  E5B9B4
                                                                                                                                                                                |   E697B6
                                                                                                                                                                                |
                                                                                                                                                                                |  
                                                                ///         //                                                                | 
                                                               ///         //                          ///         //                         |
                                                            ///          //                           ///         //                          |
                                                          ///           \\                           ///         //                           |
                                                          ///           \\                          ///         //                            |
                                                            ///         \\                         ///         //                             |
                                                            ///        \\                         ///         //                              |
                                                            //         \\                       //           //                                            |
                                                           <E5BE90 E6A3AE                     < E697A0 E685BA                                              |



    ______________________
    < designer BY wu wang  >
    ----------------------

*/